package org.dromara.system.listener;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HtmlUtil;
import cn.idev.excel.context.AnalysisContext;
import cn.idev.excel.event.AnalysisEventListener;
import jakarta.validation.ConstraintViolation;
import jakarta.validation.ConstraintViolationException;
import lombok.extern.slf4j.Slf4j;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.utils.SpringUtils;
import org.dromara.common.core.utils.StreamUtils;
import org.dromara.common.core.utils.ValidatorUtils;
import org.dromara.common.core.validate.AddGroup;
import org.dromara.common.excel.core.ExcelListener;
import org.dromara.common.excel.core.ExcelResult;
import org.dromara.system.domain.SysUserMachine;
import org.dromara.system.domain.bo.MachinePutBo;
import org.dromara.system.domain.bo.SysUserMachineBo;
import org.dromara.system.domain.vo.SysUserMachineVo;
import org.dromara.system.service.ISysUserMachineService;

import java.util.List;

@Slf4j
public class SysUserMachineListener extends AnalysisEventListener<SysUserMachineVo> implements ExcelListener<SysUserMachineVo> {

    private final ISysUserMachineService machineService;
    private final StringBuilder successMsg = new StringBuilder();
    private final StringBuilder failureMsg = new StringBuilder();
    private final MachinePutBo machinePutBo;
    private int successNum = 0;
    private int failureNum = 0;

    public SysUserMachineListener(MachinePutBo machinePutBo) {
        // 显示使用构造函数，否则将导致空指针
        this.machineService = SpringUtils.getBean(ISysUserMachineService.class);
        this.machinePutBo = machinePutBo;
    }

    @Override
    public void invoke(SysUserMachineVo sysUserMachineVo, AnalysisContext analysisContext) {
        SysUserMachine sysUserMachine = this.machineService.lambdaQuery().eq(SysUserMachine::getSn, sysUserMachineVo.getSn()).one();
        try {
            // 验证是否存在这个用户
            if (ObjectUtil.isNull(sysUserMachine)) {
                SysUserMachineBo sysUserMachineBo = BeanUtil.toBean(sysUserMachineVo, SysUserMachineBo.class);
                ValidatorUtils.validate(sysUserMachineBo, AddGroup.class);
                sysUserMachineBo.setMachinePolicyId(machinePutBo.getMachinePolicyId());
                sysUserMachineBo.setBrandId(machinePutBo.getBrandId());
                sysUserMachineBo.setLineId(machinePutBo.getLineId());
                sysUserMachineBo.setMachineModelId(machinePutBo.getMachineModelId());
                sysUserMachineBo.setUserId(machinePutBo.getUserId());
                machineService.insertByBo(sysUserMachineBo);
                successNum++;
                successMsg.append("<br/>").append(successNum).append("、sn ").append(sysUserMachineBo.getSn()).append(" 导入成功");
            } else if (ObjectUtil.isNotNull(sysUserMachine) && machinePutBo.getIsSupportUpdate()) {
                sysUserMachine.setMachinePolicyId(machinePutBo.getMachinePolicyId());
                sysUserMachine.setBrandId(machinePutBo.getBrandId());
                sysUserMachine.setLineId(machinePutBo.getLineId());
                sysUserMachine.setMachineModelId(machinePutBo.getMachineModelId());
                sysUserMachine.setUserId(machinePutBo.getUserId());
                machineService.updateById(sysUserMachine);
                successMsg.append("<br/>").append(successNum).append("、sn ").append(sysUserMachine.getSn()).append(" 更新成功");
            } else {
                failureNum++;
                failureMsg.append("<br/>").append(failureNum).append("、sn ").append(sysUserMachine.getSn()).append(" 已存在");
            }
        } catch (Exception e) {
            failureNum++;
            String msg = "<br/>" + failureNum + "、sn " + HtmlUtil.cleanHtmlTag(sysUserMachineVo.getSn()) + " 导入失败：";
            String message = e.getMessage();
            if (e instanceof ConstraintViolationException cvException) {
                message = StreamUtils.join(cvException.getConstraintViolations(), ConstraintViolation::getMessage, ", ");
            }
            failureMsg.append(msg).append(message);
            log.error(msg, e);
        }
    }


    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        System.out.println("123");
    }


    @Override
    public ExcelResult<SysUserMachineVo> getExcelResult() {
        return new ExcelResult<>() {

            @Override
            public String getAnalysis() {
                if (failureNum > 0) {
                    failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
                    throw new ServiceException(failureMsg.toString());
                } else {
                    successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
                }
                return successMsg.toString();
            }

            @Override
            public List<SysUserMachineVo> getList() {
                return null;
            }

            @Override
            public List<String> getErrorList() {
                return null;
            }
        };
    }
}
